#encoding=utf8
'''
Created on Aug 17, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.contrib.admin.sites import AdminSite
from django.views.decorators.cache import never_cache
from app_info.models import ProductionTeam, UserGroup, AppVersion, APP_STORE,\
    PRODUCTION_TYPE
import itertools
from qa_info.models import DevQAInfo
from django.template.loader import get_template
from utils import JsonResponse, this_week
from django.template.context import RequestContext
import datetime


def this_monday(d):
    return d - datetime.timedelta(days=d.weekday())


def this_sunday(d):
    return this_monday(d) + datetime.timedelta(days=6)


def get_done():
    today = datetime.date.today()
    monday, sunday = this_week(today)
    teams = ['KTG Total', 'KTG 1', 'KTG 2', 'KTG 3',
             'FPG Total', 'IET', 'RUT',
             'NPD Total']
    app_stores = [x[0] for x in APP_STORE]
    prd_type = [x[1] for x in PRODUCTION_TYPE]

    summary = [0 for i in range(len(teams))]
    metrics = []

    base_data = AppVersion.objects.filter(date_submitted__range=(monday, sunday))

    met_names = [('submitted', 'Submitted'),
                 ('released', 'Released')]
    for n, m in enumerate(met_names):
        met = {'name': m[0], 'label': m[1]}
        if n == 0:
            base = base_data.filter(status='S')
        elif n == 1:
            base = base_data.filter(status='L')

        sum = [0 for i in range(len(teams))]
        data = []
        for s, t in itertools.product(app_stores, prd_type):
            v_base = base.filter(app__app_store=s, type=t[0])
            tmp = []
            for d in ['KTG', 'FPG', 'NPD']:
                d_base = v_base.filter(prd_team__group__name=d)
                tmp.append(d_base.count())
                if d == 'KTG':
                    tmp.append(d_base.filter(prd_team__name='KTG 1').count())
                    tmp.append(d_base.filter(prd_team__name='KTG 2').count())
                    tmp.append(d_base.filter(prd_team__name='KTG 3').count())
                elif d == 'FPG':
                    tmp.append(d_base.filter(prd_team__name='IET').count())
                    tmp.append(d_base.filter(prd_team__name='RUT').count())
            data.append({'label': '%s - %s' % (s, t), 'value': tmp})
            for j, k in enumerate(tmp):
                sum[j] += k
        met.update({'sum': sum, 'data': data})
        metrics.append(met)
        for f, h in enumerate(sum):
            summary[f] += h
    return {'metrics': metrics, 'summary': summary, 'teams': teams}


def get_context():
    teams = ['KTG Total', 'KTG 1', 'KTG 2', 'KTG 3',
             'FPG Total', 'IET', 'RUT',
             'NPD Total']
    app_stores = [x[0] for x in APP_STORE]
    prd_type = [x[1] for x in PRODUCTION_TYPE]

    summary = [0 for i in range(len(teams))]
    metrics = []

    met_names = [('in_production', 'In Production'),
                 ('in_dev_qa', 'Dev QA In Progress'),
                 ('in_sub', 'Submission In Progress')]
    for n, m in enumerate(met_names):
        met = {'name': m[0], 'label': m[1]}
        if n == 0:
            base = AppVersion.objects.filter(status='I')
        elif n == 1:
            dev_qa = DevQAInfo.objects.filter(status='I')
            id_list = []
            for q in dev_qa:
                v = q.get_app_version()
                if v:
                    id_list.append(v.pk)
            base = AppVersion.objects.filter(id__in=id_list)
        elif n == 2:
            vs = AppVersion.objects.filter(status__in=['I', 'O'])
            id_list = []
            for v in vs:
                sub_info = v.get_sub_info()
                if not sub_info or not sub_info.validation == 'V' or sub_info.status == 'S':
                    id_list.append(v.pk)
            base = vs.exclude(id__in=id_list)

        sum = [0 for i in range(len(teams))]
        data = []
        for s, t in itertools.product(app_stores, prd_type):
            v_base = base.filter(app__app_store=s, type=t[0])
            tmp = []
            for d in ['KTG', 'FPG', 'NPD']:
                d_base = v_base.filter(prd_team__group__name=d)
                tmp.append(d_base.count())
                if d == 'KTG':
                    tmp.append(d_base.filter(prd_team__name='KTG 1').count())
                    tmp.append(d_base.filter(prd_team__name='KTG 2').count())
                    tmp.append(d_base.filter(prd_team__name='KTG 3').count())
                elif d == 'FPG':
                    tmp.append(d_base.filter(prd_team__name='IET').count())
                    tmp.append(d_base.filter(prd_team__name='RUT').count())
            data.append({'label': '%s - %s' % (s, t), 'value': tmp})
            for j, k in enumerate(tmp):
                sum[j] += k
        met.update({'sum': sum, 'data': data})
        metrics.append(met)
        for f, h in enumerate(sum):
            summary[f] += h
    return {'metrics': metrics, 'summary': summary, 'teams': teams}


class CustomAdminSite(AdminSite):

    index_template = 'base/home.html'
    ajax_dashboard = 'base/dashboard.html'

    @never_cache
    def index(self, request, extra_context=None):
        extra_context = {'title': 'Dashboard'}
        if request.is_ajax():
            t = get_template(self.ajax_dashboard)
            html = t.render(RequestContext(request, get_context()))
            html_done = t.render(RequestContext(request, get_done()))
            return JsonResponse({'status': 1, 'html': html, 'html_done': html_done})
        return AdminSite.index(self, request, extra_context=extra_context)
